/*
 * app_main.c
 *
 *  Created on: Jun 29, 2025
 *      Author: User
 */

#include "app_main.h"
#include "bsp_includes.h"
#include "app_isr.h"
#include "iwdg.h"
#include "pvd.h"
#include "bsp_conf.h"

ErrorBuffer ErrorCan1ID;
uint8_t communicationCan1ErrorFlag = 0;

uint8_t can1ReciveFlag = 0;
uint8_t can2ReciveFlag = 0;
uint8_t can1TransmitErrorFlag = 0;
uint8_t can2TransmitErrorFlag = 0;
uint8_t can1ErrorFlag = 0;
uint8_t can2ErrorFlag = 0;

BOXSTATE boxState = BSP_NORMAL;
uint8_t temperature_flag[8] = {0x11, 0xFC};
uint32_t cumulatetime = 0;
int saveTimeFlag = 0;
uint8_t I2c_Buf_Read[4] = {0};
int uploadFlag = 0;
uint8_t versionData[8] = {BOXADDR, 0x02, (VERSION&0x0000FF), ((VERSION>>8)&0x0000FF), YEAR, MONTH, DAY, BOXID};

LoopLinkSct temperatureSample = {
		.data = {0, 0, 0, 0, 0, 0, 0, 0},
		.head = 0
};
short nowTemperature        = 0;
short lastsysTemperature    = 0;
short lastTemperature       = 0;
/**
 * @brief:控制配电箱外部LED
 *    GPIO_PIN_2--红灯
 *    GPIO_PIN_4-绿灯
 */
void BSP_DispBoxState(void)
{
	switch(boxState){
		case BSP_NORMAL:
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_2,GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_4,GPIO_PIN_RESET);
			break;
		case BSP_FAULT:
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_4,GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_2,GPIO_PIN_RESET);
			break;
		case BSP_ALARM:
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_2,GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOE,GPIO_PIN_4,GPIO_PIN_RESET);
			break;
	}
}
short myabs(short data1, short data2)
{
	short ret = data1-data2;
	ret = (data1-data2)>0?ret:(-ret);
	return ret;

}
/**
 * @brief:采集系统温度
 */
short GetSysTemperature(void)
{
	static uint8_t temptureUploadFlag = 0;
	short sysTemperature = 0;
	short temperatureArry[10];
	int   temperatureSum = 0;
	/*采集10个数据进行一次处理*/
	temperatureSample.data[temperatureSample.head] = DS18B20_Get_Temp();
	temperatureSample.head = temperatureSample.head>=9?0:(temperatureSample.head+1);
	for(int i=0;i<10;i++)
	{
		temperatureArry[i] = temperatureSample.data[i];
	}
	//排序，从小到大
	for (int i = 0;i < 10;i ++)
	{
		for (int j = 0;j < 10 - i - 1;j ++){
			if (temperatureArry[j] > temperatureArry[j+1]){
				short temp = temperatureArry[j];
				temperatureArry[j] = temperatureArry[j+1];
				temperatureArry[j+1] = temp;
			}
		}
	}
	//除去一个最大和最小，求和
	temperatureSum   = 0;
	for (int i = 1; i < 9;i ++){
		temperatureSum += temperatureArry[i];
	}
	nowTemperature = temperatureSum / 8; //平均值
	temptureUploadFlag ++;
	if (temptureUploadFlag > 10){
		if(myabs(nowTemperature,lastTemperature)<10) //检测正确
		{
			sysTemperature = nowTemperature;
			lastsysTemperature = sysTemperature;
		}
		else
		{
			sysTemperature = lastsysTemperature;
		}
		lastTemperature = nowTemperature;
		temptureUploadFlag = 10;
	}
	lastTemperature = nowTemperature;
	return sysTemperature;
}
/**
 * @breif:更新系统温度
 */
void BSP_UpdateSysTemp(void)
{
	temperature = GetSysTemperature();

	if(temperature > 450)
	{
		temperature_flag[1] = temperatureON;
	}
	else if(temperature < 0)
	{
		temperature_flag[1] = temperatureOFF;
	}else{
		if((power > 40000)){ // 电压和电流都是放大10倍上传
			temperature_flag[1] = temperatureON;
		}else if(power < 20000 && temperature < 400){
			temperature_flag[1] = temperatureOFF;
		}
	}
}
/**
 * @breif:CAN总线报文转发
 */
void BSP_FrameTransmit(void)
{
	/*****转发报文给执行模块****************/
	if(fifo0_can1_flag > 0)
	{
		for (int i = 0;i < fifo0_can1_flag;i ++){
			BSP_CAN2_Tx(rxCan1DataBuffer[i].RxHeaderID, rxCan1DataBuffer[i].RxData);
			HAL_Delay(5);
			if(rxCan1DataBuffer[i].RxHeaderID == VERSIONFRAME){
				BSP_CAN1_Transmit(VERSIONCALLBACKFRAME, versionData);
			}
		}
		fifo0_can1_flag = 0;
	}
	/*****转发报文给显控****************/
	if(fifo1_can2_flag > 0)
	{
		for (int i = 0;i < fifo1_can2_flag;i ++){
			BSP_CAN1_Transmit(rxCan2DataBuffer[i].RxHeaderID, rxCan2DataBuffer[i].RxData);
			HAL_Delay(5);
		}
		fifo1_can2_flag = 0;
	}
}
/**
 * @brief:CAN总线通信故障检测
 */
void BSP_CanErrorMonitor(void)
{
	if (can1TransmitErrorFlag > UPLOADDATASIZE * 9 || can1ReciveFlag > DATABUFFERSIZE * 10){
		can1TransmitErrorFlag =  0;
		can1ReciveFlag = 0;
		BSP_CAN1_Config();
	}

	if (can2TransmitErrorFlag > 20 || can2ReciveFlag > DATABUFFERSIZE * 10){
		can2TransmitErrorFlag = 0;
		can2ReciveFlag = 0;
		BSP_CAN2_Config();
	}
}
/**
 * @brief:主控检测显控的运行报文,5s内未收到控制报文
 */
void BSP_XKComMonitor(void)
{
	ErrorCan1ID.errortimes ++;
	if (ErrorCan1ID.errortimes > JUDEMENTDELAYTIMES){  //5s未收到控制报文
		communicationCan1ErrorFlag = 1;
		ErrorCan1ID.errortimes = JUDEMENTDELAYTIMES;
	}
	else
	{
		communicationCan1ErrorFlag = 0;
	}
}


void APP_Init(void)
{
	BSP_DataInit();
	HAL_IWDG_Refresh(&hiwdg);
	BSP_CAN1_Config();
	BSP_CAN2_Config();
	BSP_MX_TIM3_Config();
	PVD_Config();
}

void APP_Run(void)
{
	BSP_UpdateSysTemp();          //更新系统温度
	BSP_FrameTransmit();          //报文转发
	if(time_flag == 1)            //
	{
		Upload_To_Xiankong();     //运行报文上传
		BSP_CanErrorMonitor();    //CAN总线检测
		BSP_XKComMonitor();       //显控通信故障检测
		BSP_UpdateBoxState();     //更新配电箱的状态
		BSP_DispBoxState();        //控制配电箱LED
		BSP_CheckModulesComError();//执行板掉线检测5s未收到运行报文
		saveTimeFlag ++;
		if (saveTimeFlag == 120){
			cumulatetime ++;
			saveTimeFlag = 0;
		}
//		BSP_CAN2_Tx(temperatureID, temperature_flag);//20250630 删除温度控制报文
		LED1_RUN;
		time_flag = 0;
	}
	HAL_IWDG_Refresh(&hiwdg);
}
